<?php
// $Id: edit.php,v 2.1.2 2005/04/06 13:21:00 Yoshi.Sakai Exp $
require('header.php');
include_once XOOPS_ROOT_PATH."/include/xoopscodes.php";
include_once('pop.ini.php');		// Load init file
include_once('thumb.php');

	if (!empty($xoopsUser)) $admin = $xoopsUser->isAdmin();
	
	if(!$xoopsUser || !is_object($xoopsUser)){
		redirect_header(XOOPS_URL.'/modules/popnupblog/',2,_MD_POPNUPBLOG_CAN_WRITE_USER_ONLY);
		exit();
	}
	if(!xoops_refcheck()){
		redirect_header(XOOPS_URL.'/modules/popnupblog/',2,'Referer Check Failed');
		exit();
	}
	$debug = 0;
	$confirm_mailalias = isset($HTTP_POST_VARS['confirm_mailalias']) ? 'on' : 'off';
	$confirm_mailsends = isset($HTTP_POST_VARS['confirm_mailsends']) ? 'on' : 'off';
	$add_mailalias = isset($HTTP_POST_VARS['add_mailalias']) ? 'on' : 'off';
	$add_mailsends = isset($HTTP_POST_VARS['add_mailsends']) ? 'on' : 'off';
	$remove_mailalias = isset($HTTP_POST_VARS['remove_mailalias']) ? 'on' : 'off';
	$remove_mailsends = isset($HTTP_POST_VARS['remove_mailsends']) ? 'on' : 'off';
	$updatepreference = isset($HTTP_POST_VARS['updatepreference']) ? 'on' : 'off';
	$commit = isset($HTTP_POST_VARS['commit']) ? 'on' : 'off';
	$preview = isset($HTTP_POST_VARS['preview']) ? 'on' : 'off';
	$delete = isset($HTTP_POST_VARS['delete']) ? 'on' : 'off';
	$blogid = isset($HTTP_POST_VARS['blogid']) ? $HTTP_POST_VARS['blogid'] :PopnupBlogUtils::get_blogid_from_uid($xoopsUser->uid());
	$bloginfo = array();
	$bloginfo = PopnupBlogUtils::get_bloginfo($xoopsUser->uid());
	$today = isset($HTTP_GET_VARS['today']) ? $HTTP_GET_VARS['today'] : '';

//	if(!$blog->canWrite() && ($HTTP_GET_VARS['today'] == 'on') ){
	if($add_mailalias == 'on') {
		if ($HTTP_POST_VARS['emailalias_txt']){
			$alias_uid = $HTTP_POST_VARS['alias_uid'];
			if(!$alias_uid) $alias_uid = 0; 
			PopnupBlogUtils::mailalias_add($HTTP_POST_VARS["bid"],1,$HTTP_POST_VARS["emailalias_txt"],$alias_uid);
		}
		$xoopsTpl->assign('bloginfo',PopnupBlogUtils::getBlogInfo($xoopsUser->uid()));
		$xoopsOption['template_main'] = 'popnupblog_application.html';
	}elseif($confirm_mailalias == 'on') {
		if ($HTTP_POST_VARS['alias_uname']){
			$myrow = PopnupBlogUtils::find_uid_mail($HTTP_POST_VARS['alias_uname']);
			$alias_uid = $myrow[0];
			$alias_email = $myrow[1];
			$xoopsTpl->assign('alias_uname',$HTTP_POST_VARS['alias_uname']);
			$xoopsTpl->assign('alias_uid',$alias_uid);
			$xoopsTpl->assign('alias_email',$alias_email);
		}
		$xoopsTpl->assign('bloginfo',PopnupBlogUtils::getBlogInfo($xoopsUser->uid()));
		$xoopsOption['template_main'] = 'popnupblog_application.html';
	}elseif($remove_mailalias == 'on') {
		$bid = isset($HTTP_POST_VARS['bid']) ? intval($HTTP_POST_VARS['bid']) : 0;
		if ($HTTP_POST_VARS['emailalias']){
			PopnupBlogUtils::mailalias_delete($HTTP_POST_VARS["bid"],1,$HTTP_POST_VARS['emailalias']);
		}
		$xoopsTpl->assign('bloginfo',PopnupBlogUtils::getBlogInfo($xoopsUser->uid()));
		$xoopsOption['template_main'] = 'popnupblog_application.html';
	}elseif($confirm_mailsends == 'on') {
		if ($HTTP_POST_VARS['sends_uname']){
			$myrow = PopnupBlogUtils::find_uid_mail($HTTP_POST_VARS['sends_uname']);
			$sends_uid = $myrow[0];
			$sends_email = $myrow[1];
			$xoopsTpl->assign('sends_uname',$HTTP_POST_VARS['sends_uname']);
			$xoopsTpl->assign('sends_uid',$sends_uid);
			$xoopsTpl->assign('sends_email',$sends_email);
		}
		$xoopsTpl->assign('bloginfo',PopnupBlogUtils::getBlogInfo($xoopsUser->uid()));
		$xoopsOption['template_main'] = 'popnupblog_application.html';
	}elseif($add_mailsends == 'on') {
		if ($HTTP_POST_VARS['emailsends_txt']){
			$sends_uid = $HTTP_POST_VARS['sends_uid'];
			if(!$sends_uid) $sends_uid = 0; 
			PopnupBlogUtils::mailalias_add($HTTP_POST_VARS["bid"],2,$HTTP_POST_VARS["emailsends_txt"],$sends_uid);
		}
		$xoopsTpl->assign('bloginfo',PopnupBlogUtils::getBlogInfo($xoopsUser->uid()));
		$xoopsOption['template_main'] = 'popnupblog_application.html';
	}elseif($remove_mailsends == 'on') {
		$bid = isset($HTTP_POST_VARS['bid']) ? intval($HTTP_POST_VARS['bid']) : 0;
		if ($HTTP_POST_VARS['emailsends']){
			PopnupBlogUtils::mailalias_delete($HTTP_POST_VARS["bid"],2,$HTTP_POST_VARS['emailsends']);
		}
		$xoopsTpl->assign('bloginfo',PopnupBlogUtils::getBlogInfo($xoopsUser->uid()));
		$xoopsOption['template_main'] = 'popnupblog_application.html';
	}elseif($updatepreference == 'on') {
		$targetBid = isset($HTTP_POST_VARS['bid']) ? intval($HTTP_POST_VARS['bid']) : 0;
		$targetGid = isset($HTTP_POST_VARS['gid']) ? intval($HTTP_POST_VARS['gid']) : 0;
		$cat_id = isset($HTTP_POST_VARS['cat_id']) ? intval($HTTP_POST_VARS['cat_id']) : 0;
		$canread    = isset($HTTP_POST_VARS['canread'])    ? intval($HTTP_POST_VARS['canread'])    : 0;
		$cancomment = isset($HTTP_POST_VARS['cancomment']) ? intval($HTTP_POST_VARS['cancomment']) : 0;
		$canvote    = isset($HTTP_POST_VARS['canvote'])    ? intval($HTTP_POST_VARS['canvote'])    : 0;
		$permission = $canread + $cancomment + $canvote;
		$title = isset($HTTP_POST_VARS['title']) ? ($HTTP_POST_VARS['title']) : "";
		$desc = isset($HTTP_POST_VARS['desc']) ? ($HTTP_POST_VARS['desc']) : "";
		$email = isset($HTTP_POST_VARS['email']) ? ($HTTP_POST_VARS['email']) : "";
		//      Modified by hoshiyan@hoshiba-farm.com 2004.8.4
		//$emailalias = isset($HTTP_POST_VARS['emailalias']) ? ($HTTP_POST_VARS['emailalias']) : "";
		if($xoopsUser->uid()){
			if($permission >= 0){
				$blog = new PopnupBlog($targetBid);
				$blog->setBlogInfo($targetGid, $cat_id, $permission, $title, $desc, $email);
				//PopnupBlogUtils::setEmailAliasInfo($targetBid,$emailalias);
			}
		}
		$xoopsTpl->assign('bloginfo',PopnupBlogUtils::getBlogInfo($xoopsUser->uid()));
		$xoopsOption['template_main'] = 'popnupblog_application.html';
	}elseif($today == 'preference'){
		if((!empty($xoopsModuleConfig['POPNUPBLOG_APPL'])) && ($xoopsModuleConfig['POPNUPBLOG_APPL'] == 1) ){
			redirect_header(XOOPS_URL.'/',1,_MD_POPNUPBLOG_NORIGHTTOACCESS.'(1.2)');
			exit();
		}
		$xoopsTpl->assign('bloginfo',PopnupBlogUtils::getBlogInfo($xoopsUser->uid()));
		$member_handler =& xoops_gethandler('member');
		$groupnames = $member_handler->getGroupList(); 
		$xoopsTpl->assign('groupselect', PopnupBlogUtils::mkselect('gid',$groupnames, null));
		$categories = PopnupBlogUtils::get_categories();
		$xoopsTpl->assign('categories', PopnupBlogUtils::mkselect('cat_id',$categories,null));
		$xoopsOption['template_main'] = 'popnupblog_application.html';
	}elseif((!$bloginfo && $today == 'on') || ($today == 'apply')){
		if((!empty($xoopsModuleConfig['POPNUPBLOG_APPL'])) && ($xoopsModuleConfig['POPNUPBLOG_APPL'] == 1) ){
			redirect_header(XOOPS_URL.'/',1,_MD_POPNUPBLOG_NORIGHTTOACCESS.'(1.2)');
			exit();
		}
		$member_handler =& xoops_gethandler('member');
		$groupnames = $member_handler->getGroupList(); 
		$xoopsTpl->assign('groupselect', PopnupBlogUtils::mkselect('gid',$groupnames, null));
		$categories = PopnupBlogUtils::get_categories();
		$xoopsTpl->assign('categories', PopnupBlogUtils::mkselect('cat_id',$categories,null));
		$xoopsOption['template_main'] = 'popnupblog_application.html';
	}else{
		$params = PopnupBlogUtils::getDateFromHttpParams();
		$dates = PopnupBlogUtils::complementDate($params);
		//
		// Get Server time by hoshiyan, hoshiba-farm.com 2004.07.15
		//
		if ( $xoopsUser ) { 
			$userTZ = $xoopsUser->getVar("timezone_offset");
		} else { 
			$userTZ = $xoopsConfig['default_TZ'];
		}
		$server_dates = array();
		$user_time = mktime($dates['hours'],$dates['minutes'],$dates['seconds'],$dates['month'],$dates['date'],$dates['year']);
		$server_time = userTimeToServerTime($user_time,$userTZ);
		$server_dates['year'] = strftime("%Y", $server_time);
		$server_dates['month'] = strftime("%m", $server_time);
		$server_dates['date'] = strftime("%d", $server_time);
		$server_dates['hours'] = strftime("%H", $server_time);
		$server_dates['minutes'] = strftime("%M", $server_time);
		$server_dates['seconds'] = strftime("%S", $server_time);
		if ($debug) { print( $userTZ ); }
		//if ($debug) { print_r( $dates ); }
		if ($debug) { print_r($server_dates); }
//print_r($params);
		if($delete == 'on'){
			$blog = new PopnupBlog($blogid);
			if($blog->updateBlog($server_dates, null, null,$params['blogid'])){	//if($blog->updateBlog($dates, null, null,$params['blogid'])){
				redirect_header(PopnupBlogUtils::createUrl($params['blogid']),2,_MD_POPNUPBLOG_BLOG_UPDATE);
				exit();
			}else{
				redirect_header(PopnupBlogUtils::createUrl($params['blogid']),2,_MD_POPNUPBLOG_INTERNALERROR.'(0.2)');
				exit();
			}
		} elseif($commit == 'on') {
			if ($blogid!=$params['blogid']) $params['blogid']=$blogid;
			if (!$params['blogid']) $params['blogid'] = substr($params['params'],0,1);
			$blog = new PopnupBlog($params['blogid']);
			$title = isset($HTTP_POST_VARS['title']) ? $HTTP_POST_VARS['title'] : '';
			$text = get_uploadfile(isset($HTTP_POST_VARS['text']) ? $HTTP_POST_VARS['text'] : '',$blog->permission);
			if($blog->updateBlog($server_dates, $text, $title,$params['blogid'])){		//if($blog->updateBlog($dates, $text, $title,$params['blogid'])){
				redirect_header(PopnupBlogUtils::createUrl($params['blogid']),2,_MD_POPNUPBLOG_BLOG_UPDATE);
				exit();
			}else{
				redirect_header(PopnupBlogUtils::createUrl($params['blogid']),2,_MD_POPNUPBLOG_INTERNALERROR.'(0.2)');
				exit();
			}
		}else{
			if($preview == 'on'){
				$selectblog = "(".$blogid.") ".PopnupBlogUtils::mkselect("blogid",$bloginfo,$blogid);
				$ts =& MyTextSanitizer::getInstance();
				$blog = new PopnupBlog($blogid);
				$text = get_uploadfile($HTTP_POST_VARS['text'],$blog->permission);
				$formValue['text'] = $text;
				$formValue['text'] = $ts->previewTarea($formValue['text'], 0, 1, 1, 1, 1);
				$formValue['text_edit'] = $text;
				$formValue['text_edit'] = $ts->makeTboxData4PreviewInForm($formValue['text_edit']);
				$formValue['title'] = $HTTP_POST_VARS['title'];
				$formValue['title'] = $ts->makeTboxData4PreviewInForm($formValue['title']);
				$formValue['trackback'] = $HTTP_POST_VARS['trackback'];
				$formValue['year']  = $dates['year'];
				$formValue['month']  = $dates['month'];
				$formValue['date']  = $dates['date'];
				$formValue['hours']  = $dates['hours'];
				$formValue['minutes']  = $dates['minutes'];
				$formValue['seconds']  = $dates['seconds'];
				echo "<p><table class='outer' cellspacing='1'>\n";
				echo "<tr><th>"._MD_POPNUPBLOG_FORM_PREVIEW."</th></tr>\n";
				echo '<tr class="even"><td><div class="comText">'.$formValue['text'].'</div></td></tr>';
				echo "</table></p>\n";
			}else{
				if (!(empty($params['year'])) && !($today=='on')){
				//	if ($admin){
					$blogid = $params['blogid'];
					$blog = new PopnupBlog($params['blogid']);
					$result = $blog->getBlog1($server_dates,$params['blogid']);	
					//$selectblog = "(".$blogid.") ".$bloginfo[$blogid].
					$selectblog = "(".$blogid.") ".$blog->title.
						'<input type="hidden" name="blogid" value="'.$blogid.'" />'."\n";
				//	} else {
				//		$result = $blog->getBlog1($server_dates);	//$result = $blog->getBlog1($dates);
				//	}
					$formValue['text']  = array_key_exists('text', $result)  ? $result['text']  : "";
					$formValue['text_edit']  = array_key_exists('text_edit', $result)  ? $result['text_edit']  : "";
					$formValue['title'] = array_key_exists('title', $result) ? $result['title'] : "";
					$formValue['year']  = array_key_exists('year', $result)  ? $result['year']  : "";
					$formValue['month']  = array_key_exists('month', $result)  ? $result['month']  : "";
					$formValue['date']  = array_key_exists('date', $result)  ? $result['date']  : "";
					$formValue['hours']  = array_key_exists('hours', $result)  ? $result['hours']  : "";
					$formValue['minutes']  = array_key_exists('minutes', $result)  ? $result['minutes']  : "";
					$formValue['seconds']  = array_key_exists('seconds', $result)  ? $result['seconds']  : "";
					$formValue['trackback'] = '';
				} else {
					$selectblog = "(".$blogid.") ".PopnupBlogUtils::mkselect("blogid",$bloginfo,$blogid);
					$formValue['text_edit'] = '';
					$formValue['title'] = '';
					$formValue['trackback'] = '';
					$formValue['year']  = $dates['year'];
					$formValue['month']  = $dates['month'];
					$formValue['date']  = $dates['date'];
					$formValue['hours']  = $dates['hours'];
					$formValue['minutes']  = $dates['minutes'];
					$formValue['seconds']  = $dates['seconds'];
				}
			}
			$GLOBALS['text'] = $formValue['text_edit'];
			echo "<!-- begin of popnupblog edit form -->\n";
			echo "<table class='outer' cellspacing='1'>\n";
			echo "<form method=\"post\" enctype=\"multipart/form-data\" action=\"".XOOPS_URL."/modules/popnupblog/edit.php\">";
			echo '<tr><td align="left" class="head">'._MD_POPNUPBLOG_FORM_SELECTBLOG.'</td><td>';
			echo $selectblog;
//			echo '<input type="submit" value="'._MD_POPNUPBLOG_FORM_SWITCH.'" name="preview"/>';
			echo "</td></tr>\n";
			echo "<tr><td align='left' class='head'>"._MD_POPNUPBLOG_FORM_TITLE."</td>";
			echo "<td align='left' class='even'><input type='text' name='title' size='70' value='".$formValue['title']."' />";
			if (!empty($params['year'])){
				echo '&nbsp;'._MD_POPNUPBLOG_FORM_DATE.'&nbsp;'.
				$formValue['year'].'-'.$formValue['month'].'-'.$formValue['date'].' '.$formValue['hours'].':'.$formValue['minutes'].':'.$formValue['seconds'].'</td></tr>';
			}
			echo "<tr><td align='left' class='head'>Trackback URL</td><td class='even'><input type='text' name='trackback' size='70' value='".$formValue['trackback']."' /></td></tr>\n";
			echo '<tr><td align="left" class="head">'._MD_POPNUPBLOG_FORM_CONTENS."</td>\n";
			echo '<td class="even" >';
			echo '<input type="hidden" name="year" value="'.$formValue['year'].'" />'."\n";
			echo '<input type="hidden" name="month" value="'.$formValue['month'].'" />'."\n";
			echo '<input type="hidden" name="date" value="'.$formValue['date'].'" />'."\n";
			echo '<input type="hidden" name="hours" value="'.$formValue['hours'].'" />'."\n";
			echo '<input type="hidden" name="minutes" value="'.$formValue['minutes'].'" />'."\n";
			echo '<input type="hidden" name="seconds" value="'.$formValue['seconds'].'" />'."\n";
			echo '<input type="hidden" name="param" value="'.$params['blogid']."-".$formValue['year'].$formValue['month'].$formValue['date'].$formValue['hours'].$formValue['minutes'].$formValue['seconds'].'" />'."\n";
			xoopsCodeTarea('text');
			xoopsSmilies('text');
			//
			// File upload By Yoshi.Sakai, bluemooninc.biz 2004/3/14
			//
			if (is_object($xoopsUser)){
				echo "</td></tr><tr><td class='head' valign='top' nowrap='nowrap'>Upload File</td>\n";
				echo "<td class='even'><INPUT TYPE='hidden' NAME='MAX_FILE_SIZE' VALUE='maxbyte'>";
				if ($BlogCNF['maxbyte']>=1000000){
					$maxbyte_str = sprintf("%d M",$BlogCNF['maxbyte']/1000000);
				} elseif ($BlogCNF['maxbyte']>=1000){
					$maxbyte_str = sprintf("%d K",$BlogCNF['maxbyte']/1000);
				} else {
					$maxbyte_str = sprintf("%d ",$BlogCNF['maxbyte']);
				}
				echo "<INPUT type='file' size='50' name='upfile'> Max".$maxbyte_str."Byte.";
			}
			// upload end.
			echo '</td></tr><tr><td align="center" colspan="2" class="odd">
				<input type="submit" value="'._MD_POPNUPBLOG_FORM_DELETE.'" name="delete"/> &nbsp 
				<input type="submit" value="'._MD_POPNUPBLOG_FORM_PREVIEW.'" name="preview"/> &nbsp 
				<input type="submit" value="'._MD_POPNUPBLOG_FORM_SEND.'" name="commit"/>';
			echo "<!-- begin of popnupblog edit form -->\n";
			echo "</td></tr></form>\n";
			echo "</table>\n";
		}
	}
	require('footer.php');
/*
** Get upload file by Yoshi.Sakai, bluemooninc.biz 2004/3/14
*/
function get_uploadfile($text,$permission=0) {
	global $xoopsUser,$BlogCNF;
	$permission = sprintf("%03d",$permission);
	$addmsg = $text;
	$upfile        = $_FILES['upfile'];
	$upfile_tmp    = $_FILES['upfile']['tmp_name'];	// Temp File name
	$upfile_name    = $_FILES['upfile']['name'];    // Local File Name
	$upfile_size    = $_FILES['upfile']['size'];        // Size
	$upfile_type    = $_FILES['upfile']['type'];        // Type
	if ($upfile_tmp != "" && is_object($xoopsUser)){
		// Disp File Infomation for debug
		/*
		print("File Infomation:<BR>\n");
		print("File From : $upfile_tmp<BR>\n");
		print("File To : $upfile_name<BR>\n");
		print("File Size - $upfile_size<BR>\n");
		print("File type - $upfile_type<BR>\n");
		*/
		if (eregi($BlogCNF['imgtype'].'|'.$BlogCNF['embedtype'], $upfile_type)){
			$upfile_localname=$xoopsUser->getVar('uname')."_".time().$permission."_".cnv_mbstr($upfile_name);		// convert for mbstrings
			$upfile_url = XOOPS_URL.$BlogCNF['img_dir'].rawurlencode($upfile_localname);
			$upfile_path = XOOPS_ROOT_PATH.$BlogCNF['img_dir'].$upfile_localname;
			move_uploaded_file($upfile_tmp,$upfile_path);
			//chmod($upfile_path,0777);
			// Thumbs Support ( PHP GD Libraly Required )
			if (eregi($BlogCNF['thumb_ext'],$upfile_localname)) {
				$size = getimagesize($upfile_path);
				if ($size[0] > $BlogCNF['w'] || $size[1] > $BlogCNF['h']) {
					$thumbfilename = thumb_create($upfile_path,$BlogCNF['w'],$BlogCNF['h'],XOOPS_ROOT_PATH.$BlogCNF['thumb_dir']);
					$addimg = "[url=".$upfile_url."][img align=left]".XOOPS_URL.$BlogCNF['thumb_dir'].rawurlencode($thumbfilename)."[/img][/url]";
				} else {
					$addimg = "[img align=left]".$upfile_url."[/img]";
				}
			} elseif (eregi($BlogCNF['embedtype'], $upfile_type)){
				$addimg .= "\n<EMBED src=\"".$upfile_url."\" WIDTH=\"".$BlogCNF['w']."\" HEIGHT=\"".$BlogCNF['h'].
				"\" autostart=\"false\" controller=\"true\" hspace=\"5\" align=\"left\" alt=\"\"></EMBED>\n";
			} else {
				$addimg = "[img align=left]".$upfile_url."[/img]";
			}
			$addmsg = $addimg.$addmsg;
		} else {
			$upfile_localname=$xoopsUser->getVar('uname')."_".$upfile_name.".".time().$permission;
			$upfile_url="/".rawurlencode($upfile_localname);	// XOOPS_UPLOAD_URL.
			$upfile_localname = cnv_mbstr($upfile_localname);		// convert for mbstrings
   	    	move_uploaded_file($upfile_tmp, $BlogCNF['uploads'].$upfile_localname);
			//chmod($upfile_path,0777);
			$addmsg .= "\n:download:";
			$addmsg .= "[url=".$BlogCNF['root']."download.php?url=".$upfile_url."]".$upfile_name."[/url]\n";
		}
	}
	return $addmsg;
}
/*
** Support for Multi-byte filename. By Yoshi.Sakai, bluemooninc.biz  2004/4/11
*/
function cnv_mbstr($str) {
	global $BlogCNF;

	if (extension_loaded('mbstring')){
		return  mb_convert_encoding($str,$BlogCNF['save_as_mbstr'],"auto");
	} else {
		return $str;
	}
}
?>
